<template>
  <el-dialog v-if="dialogVisible" v-model="dialogVisible" title="添加商品">
    <el-form ref="formRef" :model="formData" :label-width="'120px'">
      <el-form-item
        label="模板名称"
        prop="ruleName"
        :rules="[
          { required: true, message: '商品名称不能为空' },
          { type: 'string', message: '商品名称不合法' },
        ]"
      >
        <el-input
          v-model="formData.ruleName"
          style="max-width: 200px"
          placeholder="请添加模板名称"
        />
      </el-form-item>

      <template v-for="(item, i) in formData.ruleValue" :key="i">
        <el-form-item
          label="规格名称"
          :prop="`ruleValue[${i}].value`"
          :rules="[
            { required: true, message: '商品名称不能为空' },
            { type: 'string', message: '商品名称不合法' },
          ]"
        >
          <div style="width: 100%; display: flex">
            <el-input
              v-model.trim="item.value"
              style="max-width: 200px"
              placeholder="请添加规格名称"
            ></el-input>

            <el-button
              style="margin-left: 10px"
              type="danger"
              @click="delPrivateSpec(i)"
              >删除</el-button
            >
          </div>
        </el-form-item>

        <el-form-item>
          <div class="tag-box">
            <el-tag
              v-for="(tag, tagIndex) in item.detail"
              :key="tag"
              class="attr-tag"
              closable
              :disable-transitions="false"
              @close="handleClose(i, tagIndex)"
            >
              {{ tag }}
            </el-tag>

            <div class="add-tag-input-box">
              <el-input
                v-if="item.inputVisible"
                ref="InputRef"
                v-model.trim="item.inputValue"
                class="input-new-tag"
                size="small"
                @keyup.enter="handleInputConfirm(i, item.inputValue as string)"
                @blur="handleInputConfirm(i, item.inputValue as string)"
              />
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(i)"
              >
                + 添加属性
              </el-button>
            </div>
          </div>
        </el-form-item>
      </template>

      <el-form-item>
        <el-button type="success" @click="addSpecs()">添加规格</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch,
  onMounted,
  getCurrentInstance,
  PropType,
} from 'vue'
import { ElInput } from 'element-plus'

import { useRouter } from 'vue-router'

import { objectEntries, useVModels } from '@vueuse/core'

import * as Api from '@/api/goods/admin-attribute'
import { AttributeList } from '@/api/goods/admin-attribute'

import type { FormInstance } from 'element-plus'
import { updateReq } from '@/utils/http/code'

/**
 * 父传子
 * 固定格式
 */
const emit = defineEmits(['update:dialogVisible', 'refreshTable'])
const props = defineProps({
  /**
   * 是否显示弹窗
   */
  dialogVisible: {
    type: Boolean,
    default: false,
  },

  //商品参数详情数据(父组件请求传值过来)
  formData: {
    type: Object as PropType<FormData>,
    default: () => {
      return {}
    },
  },
})

const { formData } = toRefs(props)

const { dialogVisible } = useVModels(props)

//表单dom
const formRef = ref<FormInstance>()

/**
 * 弹窗确定按钮
 */
const submitForm = () => {
  //element自带的表单校验
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (valid) {
      console.log('校验通过')

      const res = await Api.updateAttribute(formData.value.id, formData.value)

      updateReq(res, () => {
        dialogVisible.value = false
        emit('refreshTable')
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

/**
 * 删除规格
 * @param index
 */
const delPrivateSpec = (index: any) => {
  formData.value.ruleValue.splice(index, 1)
}

/**
 * 添加规格操作初始值
 */
const addSpecs = (index: number) => {
  formData.value.ruleValue.forEach((v) => {
    v.inputVisible = false
  })
  formData.value.ruleValue.push({
    inputValue: '',
    inputVisible: false,
    value: '',
    detail: [],
  })
  if (formData.value.ruleValue[index].inputValue == '') {
    return
  }
}
//

const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
/**
 * 删除规格
 * @param index
 * @param tagIndex
 */
const handleClose = (index: number, tagIndex: number) => {
  formData.value.ruleValue[index].detail.splice(tagIndex, 1)
}
/**
 * 输入框不能为空
 */
const showInput = (i: number) => {
  if (formData.value.ruleValue[i].value == '') {
    return
  }

  inputVisible.value = true
  formData.value.ruleValue[i].inputVisible = true
}
/**
 * 添加规格
 * @param index
 * @param inputValue
 */
const handleInputConfirm = (index: number, inputValue: string) => {
  //规格值不能为空
  nextTick(() => {
    if (formData.value.ruleValue[index].inputValue == '') {
      formData.value.ruleValue[index].inputVisible = false
      return
    }
    //添加规格值
    if (formData.value.ruleValue[index].inputValue) {
      formData.value.ruleValue[index].detail.push(inputValue)
    }
    formData.value.ruleValue[index].inputValue = ''
    formData.value.ruleValue[index].inputVisible = false
    //每添加完一个失去焦点
  })
}

interface AttrList {
  inputValue?: ''
  inputVisible?: boolean
  value: string
  detail: string[]
}

interface FormData {
  id: number
  ruleName: string
  ruleValue: AttrList[]
  state: number
}
</script>
<style lang="scss" scoped>
.attr-tag {
  height: 30px;
  margin: 0 5px;
}

.tag-box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.add-tag-input-box {
  display: flex;
  .input-new-tag {
    width: 100px;
    height: 30px;
    margin: 10px 5px;
  }
  .button-new-tag {
    height: 30px;
    margin: 10px 5px;
  }
}
</style>
